
package com.roc.web.action.setting;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction; // import com.roc.pojo.Merchant;
import com.roc.pojo.CalcuBean;
import com.roc.pojo.Operators;
import com.roc.pojo.SettingBean;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService; // import
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.setting.ISettflagService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.web.action.MerchantSearchCondition;

/**
 * @author Feng haitao
 * 
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/setting")
public class CalcuAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5236170890634487270L;
	private Logger logger = LogManager.getLogger(CalcuAction.class);
	private Operators operators;
	private List<Object> profitRsList = new ArrayList<Object>();
	private CalcuSearchCondition searchCondition;

	private String msg;

	@Autowired
	IPagenitionService pagenitionService;

	@Autowired
	IorgService orgService;
	@Autowired
	ISettflagService settflagService;
	private String batchno;
	private String merchantno;

	// 清算初始页面。

	@Action(value = "calculist", results = {
			@Result(name = "success", location = "/pages/setting/calculist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	public String calculist() throws Exception {
		initSomeDataForAction();
		searchCondition = new CalcuSearchCondition();
		searchCondition.setSettFlag("Y");
		return SUCCESS;
	}

	// 清算查询
	@Action(value = "calcusearch", results = {
			@Result(name = "success", location = "/pages/setting/calculist.jsp"),
			@Result(name = "error", location = "/pages/setting/calculist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String search() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		

		if (searchCondition == null) {
			searchCondition = (CalcuSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new CalcuSearchCondition();
			}
		}
		try {
			// 系统管理员查看全部，代理只能看到本机构下的。
//			if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
//					.getRoleType())) {
//				searchCondition.setOrgCode(logingMerchant.getOrgCode());
//			}
			List<Object> objs = settflagService.querycalcuSummoney(searchCondition);
			int rows = pagenitionService.countSQL(searchCondition);
			List<CalcuBean> calcuList = new ArrayList<CalcuBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						
						Object[] obj = (Object[]) iterator.next();
						CalcuBean calcu = new CalcuBean();
						if (obj[0] != null && !"".equals(obj[0])) {
							calcu.setMerno(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							calcu.setRealname(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							calcu.setEtstermid(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							calcu.setAccount(obj[3].toString());
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							calcu.setRespcode(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							calcu.setTermtrace(obj[5].toString());
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							calcu.setEtstrace(obj[6].toString());
							calcu.setSystemno(obj[6].toString().substring(6, 12));
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							calcu.setTermtime(obj[7].toString());
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							calcu.setTermdate(obj[8].toString());
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							calcu.setAmount(Double.valueOf(obj[9].toString()));
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							calcu.setMerfee(Double
									.valueOf((obj[10].toString())));
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							calcu.setSettflag(obj[11].toString());
						}

						if (obj[12] != null && !"".equals(obj[12])) {
							calcu.setCalcuamount(Double.valueOf((obj[12]
									.toString())));
						}
						if (obj[13] != null && !"".equals(obj[13])) {
							calcu.setSettbatch(obj[13].toString());
						}
						if (obj[14] != null && !"".equals(obj[14])) {
							calcu.setCalcudate(obj[14].toString());
						}
						if (obj[15] != null && !"".equals(obj[15])) {
							calcu.setPeriod(obj[15].toString());
						}
						calcuList.add(calcu);
					}
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			double totalAmt=0;
			double totalFee=0;
			double totalCalciAmt=0;
			int count=0;
			if(objs!=null&&objs.size()>0){
				Iterator iterator = objs.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					 totalAmt=Double.valueOf(String.valueOf(obj[0]));
					 totalFee=Double.valueOf(String.valueOf(obj[1]));
					 totalCalciAmt=Double.valueOf(String.valueOf(obj[2]));
					 count=Integer.valueOf(String.valueOf(obj[3]));
				}
			}
			addActionMessage("当前条件下清算总金额【"+totalAmt+"】元，总手续费【"+totalFee+"】，总结算金额【"+totalCalciAmt+"】，总清算笔数【"+count+"】");
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("calcuList", calcuList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
		return SUCCESS;
	}

	// 结算详情查询
	@Action(value = "calcudetailsearch", results = {
			@Result(name = "success", location = "/pages/setting/calcudetaillist.jsp"),
			@Result(name = "error", location = "/pages/setting/calcudetaillist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String calcudetailsearch() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		CalcuSearchCondition search = new CalcuSearchCondition();

		if (StringUtils.isNotBlank(merchantno)) {
			search.setMerNo(merchantno);
		}
		if (StringUtils.isNotBlank(batchno)) {
			search.setBatchno(batchno);
		}
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		if (search == null) {
			search = (CalcuSearchCondition) getSearchConditionFromSession();
			if (search == null) {
				search = new CalcuSearchCondition();
			}
		}
		try {
			// 系统管理员查看全部，代理只能看到本机构下的。
			if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
					.getRoleType())) {
				search.setOrgCode(logingMerchant.getOrgCode());
			}
			int rows = pagenitionService.countSQL(search);
			List<CalcuBean> calcuList = new ArrayList<CalcuBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(search,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						CalcuBean calcu = new CalcuBean();
						if (obj[0] != null && !"".equals(obj[0])) {
							calcu.setMerno(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							calcu.setRealname(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							calcu.setEtstermid(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							calcu.setAccount(obj[3].toString());
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							calcu.setRespcode(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							calcu.setTermtrace(obj[5].toString());
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							calcu.setEtstrace(obj[6].toString());
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							calcu.setTermtime(obj[7].toString());
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							calcu.setTermdate(obj[8].toString());
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							calcu.setAmount(Double.valueOf(obj[9].toString()));
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							calcu.setMerfee(Double
									.valueOf((obj[10].toString())));
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							calcu.setSettflag(obj[11].toString());
						}

						if (obj[12] != null && !"".equals(obj[12])) {
							calcu.setCalcuamount(Double.valueOf((obj[12]
									.toString())));
						}
						if (obj[13] != null && !"".equals(obj[13])) {
							calcu.setSettbatch(obj[13].toString());
						}
						if (obj[14] != null && !"".equals(obj[14])) {
							calcu.setCalcudate(obj[14].toString());
						}
						if (obj[15] != null && !"".equals(obj[15])) {
							calcu.setPeriod(obj[15].toString());
						}
						calcuList.add(calcu);
					}
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("calcuList", calcuList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("merchantno", merchantno);
			getRequest().setAttribute("batchno", batchno);
		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
		return SUCCESS;
	}
	// 冻结单条清算或者多条查询页面
	@Action(value = "frozencalcudesearch", results = {
			@Result(name = "success", location = "/pages/setting/frozencalcudesearch.jsp"),
			@Result(name = "error", location = "/pages/setting/frozencalcudesearch.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String frozencalcudesearch() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		CalcuSearchCondition search = new CalcuSearchCondition();

		if (StringUtils.isNotBlank(merchantno)) {
			search.setMerNo(merchantno);
		}
		if (StringUtils.isNotBlank(batchno)) {
			search.setBatchno(batchno);
		}
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		if (search == null) {
			search = (CalcuSearchCondition) getSearchConditionFromSession();
			if (search == null) {
				search = new CalcuSearchCondition();
			}
		}
		try {
			// 系统管理员查看全部，代理只能看到本机构下的。
			if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
					.getRoleType())) {
				search.setOrgCode(logingMerchant.getOrgCode());
			}
			int rows = pagenitionService.countSQL(search);
			List<CalcuBean> calcuList = new ArrayList<CalcuBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(search,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						CalcuBean calcu = new CalcuBean();
						if (obj[0] != null && !"".equals(obj[0])) {
							calcu.setMerno(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							calcu.setRealname(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							calcu.setEtstermid(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							calcu.setAccount(obj[3].toString());
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							calcu.setRespcode(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							calcu.setTermtrace(obj[5].toString());
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							calcu.setEtstrace(obj[6].toString());
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							calcu.setTermtime(obj[7].toString());
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							calcu.setTermdate(obj[8].toString());
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							calcu.setAmount(Double.valueOf(obj[9].toString()));
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							calcu.setMerfee(Double
									.valueOf((obj[10].toString())));
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							calcu.setSettflag(obj[11].toString());
						}

						if (obj[12] != null && !"".equals(obj[12])) {
							calcu.setCalcuamount(Double.valueOf((obj[12]
									.toString())));
						}
						if (obj[13] != null && !"".equals(obj[13])) {
							calcu.setSettbatch(obj[13].toString());
						}
						if (obj[14] != null && !"".equals(obj[14])) {
							calcu.setCalcudate(obj[14].toString());
						}
						if (obj[15] != null && !"".equals(obj[15])) {
							calcu.setPeriod(obj[15].toString());
						}
						calcuList.add(calcu);
					}
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("calcuList", calcuList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("merchantno", merchantno);
			getRequest().setAttribute("batchno", batchno);
		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
		return SUCCESS;
	}
	
	// 冻结单条清算或者多条清算记录
	@Action(value = "frozencalcudeupdate", results = {
			@Result(name = "success", location = "/pages/setting/frozencalcudesearch.jsp"),
			@Result(name = "error", location = "/pages/setting/frozencalcudesearch.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String frozencalcudeupdate() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		CalcuSearchCondition search = new CalcuSearchCondition();

		if (StringUtils.isNotBlank(merchantno)) {
			search.setMerNo(merchantno);
		}
		if (StringUtils.isNotBlank(batchno)) {
			search.setBatchno(batchno);
		}
		
		List<String> iddlist = this.getMulti_sel_str();
		
		try {
			// 系统管理员查看全部，代理只能看到本机构下的。
			if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
					.getRoleType())) {
				search.setOrgCode(logingMerchant.getOrgCode());
			}
			int n = settflagService.querycaucleStatusCount(iddlist,batchno);
			if(n!=iddlist.size()){
				addActionMessage("选择记录"+iddlist.size()+"条，可冻结的记录"+n+"条,请重新选择。");
				return frozencalcudesearch();
			}
			//根据批次号和商户号查询结算信息。
			SettingBean oldsett = settflagService.querySettingBean(merchantno, batchno);
			
			int i =settflagService.frozencaucle(iddlist, oldsett, batchno);
		    
			if(i==0){
				addActionMessage("清算记录冻结成功");
			}else{
				addActionMessage("清算记录冻结失败");
			}
			
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			getRequest().setAttribute("merchantno", merchantno);
			getRequest().setAttribute("batchno", batchno);
		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
		return frozencalcudesearch();
	}
	
	
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/regist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }

	)
	@SuppressWarnings("unused")
	// @Validations(requiredStrings = { @RequiredStringValidator(type =
	// ValidatorType.SIMPLE, fieldName = "user.userAccount", message =
	// "请输入[登陆用户]") })
	public String init() throws Exception {
		initSomeDataForAction();
		List orgList = new ArrayList();
		try {
			Operators logingMerchant = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
					.getRoleType())) {
				orgList = orgService.lisOrgByCode(logingMerchant.getOrgCode());
			} else {
				orgList = orgService.queryOrgList();
			}

			Map<String, String> roleType = ConfigProperties
					.getRoleTypeProperties();
			getRequest().setAttribute("orgList", orgList);
			getRequest().setAttribute("roleType", roleType);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage(), e);
			addActionError("加载基本信息出错！！");
		}
		return SUCCESS;
	}

	
	
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (CalcuSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_CALCU);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_CALCU, searchCondition);
	}

	public CalcuSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(CalcuSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the profitRsList
	 */
	public List<Object> getProfitRsList() {
		return profitRsList;
	}

	/**
	 * @param profitRsList
	 *            the profitRsList to set
	 */
	public void setProfitRsList(List<Object> profitRsList) {
		this.profitRsList = profitRsList;
	}

	/**
	 * @return the profitModelHead
	 */

	public Operators getOperators() {
		return operators;
	}

	public void setOperators(Operators operators) {
		this.operators = operators;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getBatchno() {
		return batchno;
	}

	public void setBatchno(String batchno) {
		this.batchno = batchno;
	}

	public String getMerchantno() {
		return merchantno;
	}

	public void setMerchantno(String merchantno) {
		this.merchantno = merchantno;
	}

}
